package view.components
{
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	
	import model.load.DisplayObjectLoadMessage;
	import model.load.ILoadMessage;
	
	import utils.DisplayTool;
	
	public class ModulLoader extends Sprite
	{
		public var url:String;

		private var loadingBar:LoadingBar;
		private var defaultWidth:int;
		private var defaultHeight:int;
		private var _isComplete:Boolean;
		private var _content:DisplayObject;
		private var _isLoading:Boolean;
		
		public function ModulLoader(width:int,height:int)
		{
			defaultWidth = width;
			defaultHeight = height;
			
			initLoadingBar();	
		}
		
		public function get isLoading():Boolean
		{
			return _isLoading;
		}

		public function get isComplete():Boolean
		{
			return _isComplete;
		}

		private function initLoadingBar():void
		{
			loadingBar = new LoadingBar();
			if (loadingBar.width > this.defaultWidth * .6)
			{
				loadingBar.width = this.defaultWidth * .6;
				loadingBar.height *= .6;
			}
			loadingBar.x = (this.defaultWidth - loadingBar.width) * .5;
			loadingBar.y = (this.defaultHeight - loadingBar.height) * .5;
			loadingBar.percent = 0;
			addChild(loadingBar);
			
			loadingBar.addEventListener(Event.COMPLETE,onLoadingBarComplete);
		}
		
		private function onLoadingBarComplete(event:Event):void
		{
			loadingBar.removeEventListener(Event.COMPLETE,onLoadingBarComplete);
			loadingBar.x = (this.defaultWidth - loadingBar.width) * .5;
			loadingBar.y = (this.defaultHeight - loadingBar.height) * .5;
		}
		
		public function load(url:String):void
		{
			var loadMessage:ILoadMessage = new DisplayObjectLoadMessage(loadComplete,percent);
			loadMessage.url = url;
			loadMessage.send();
			_isLoading = true;
		}
		
		private function percent(v:Number):void
		{
			loadingBar.percent = v;
		}
		
		private function loadComplete(content:DisplayObject):void
		{
			
			_content = content;
			addChild(content);
			DisplayTool.removeChild(this,loadingBar);
			//addChild(loadingBar);
			_isComplete = true;
			_isLoading = false;
			dispatchEvent(new Event(Event.COMPLETE));
			
		}

		public function get content():*
		{
			return _content;
		}
		
		public function destroy():void
		{
			DisplayTool.removeAllChild(this);
			_content = null;
			loadingBar = null;
		}
	}
}